class Trace < ActiveRecord::Base
#  require "Time"
  
  belongs_to :event
  attr_accessor :hourFrom, :hourTo, :newEventTitle
  
  validates_presence_of :event_id
  validates_format_of :hourFrom, :with => /^[0-9]+:[0-9]+$/, :allow_nil => true, :message => "must be formatted properly."
  validates_format_of :hourTo, :with => /^[0-9]+:[0-9]+$/, :allow_nil => true, :message => "must be formatted properly."

  before_validation_on_create :createNewEvent
  before_save :cleanupTrace

  def self.getTodaysTraces
    return Trace.find(:all,:conditions => ["created_at > ?",Time.new.beginning_of_day])
  end

  def self.getLatest
    @traces = Trace.find(:all,:order => "created_at DESC")
    @traces = @traces[0,10]
    return @traces
  end
  
  def self.getTotalTraceTime
    @totalTraceTime = 0
    Trace.find(:all).each do |t|
      @totalTraceTime += t.minSpent
    end
    return @totalTraceTime
  end
  
  def createNewEvent
      # If the event_id field is nil, and there is text in "eventTitle"
      if (self.event_id.nil?)  # We need to make a new event...
        # If this event already exists, typed like this... lets just use that one.
        if(e = Event.find_by_title(self.newEventTitle))
          self.event_id = e.id
        else
          newEvent = Event.new(:title => self.newEventTitle, :description => "created with trace.", :client => "self")
          if (newEvent.save)
            self.event_id = newEvent.id
          else
            return false
          end
        end
      end 
  end
  
  def cleanupTrace
    # Cleanup the time spent to/from; formatted as minutes.
    if self.minSpent == 0 || self.minSpent.nil?
      tFrom = Time.parse(self.hourFrom)
      tTo   = Time.parse(self.hourTo)
      self.minSpent = (tTo-tFrom)/60
      if self.minSpent < 0 
        self.minSpent *= -1
      end
    end
    
  end
end
